package com.horizon.mobile.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.horizon.mobile.R;
import com.horizon.mobile.adapter.AgentReciveAdapter;
import com.horizon.mobile.adapter.MatterTransferAdapter;
import com.horizon.mobile.manage.SharePreferences;
import com.horizon.mobile.model.Agent;
import com.horizon.mobile.model.Result;
import com.horizon.mobile.searchdialog.SearchAct;
import com.horizon.mobile.util.HttpRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import zuo.biao.library.base.BaseHttpListActivity;
import zuo.biao.library.interfaces.AdapterCallBack;
import zuo.biao.library.interfaces.OnBottomDragListener;
import zuo.biao.library.manager.HttpManager.OnHttpResponseListener;
import zuo.biao.library.util.JSON;

/**
 * 事项移交列表
 *
 * @author 左大明
 */
public class MatterTransferListActivity extends
        BaseHttpListActivity<Agent, MatterTransferAdapter> implements
        OnBottomDragListener {
    public int page = 1;
    public String searchString = "";
    public static final String TITLE = "TITLE";
    ImageView clear_ico, search_ico, search_ico_right;
    EditText drawer_search_input;
    public List<Agent> listTodo = new ArrayList<Agent>();
    public Map<String, Agent> isCheckedMap;
    public static final String RESULT_CLICKED_ITEM = "RESULT_CLICKED_ITEM";
    Button rightButton;
    String receiveUserId = "";
    String receiveUserName = "";
    String ids = "";
    String trackIds = "";

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context, String title) {
        return new Intent(context, MatterTransferListActivity.class).putExtra(
                TITLE, title);
    }

    // 启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public Activity getActivity() {
        return this;
    }

    private String title = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO demo_list_activity改为你所需要的layout文件；传this是为了底部左右滑动手势
        setContentView(R.layout.todo_list_activity, this);
        isCheckedMap = new HashMap<String, Agent>();
        intent = getIntent();
        title = intent.getStringExtra(TITLE);
        // initCache(this);//初始化缓存，Entry<String, String>替换成不带类型的类才可使用，原因看
        // .CacheCallBack

        // 功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        // 功能归类分区方法，必须调用>>>>>>>>>>

        onRefresh();
    }

    // UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initView() {// 必须在onCreate方法内调用
        super.initView();
        drawer_search_input = (EditText) findViewById(R.id.drawer_search_input);
        clear_ico = (ImageView) findViewById(R.id.clear_ico);
        search_ico = (ImageView) findViewById(R.id.search_ico);
        rightButton = (Button) findViewById(R.id.right_btn);
        rightButton.setText("移交");
        rightButton.setVisibility(View.VISIBLE);
        search_ico_right = (ImageView) findViewById(R.id.search_ico_right);
    }

    @Override
    public void getListAsync(int page) {
        // showProgressDialog(R.string.loading);
        this.page = page;
        HttpRequest.getMatterTransferList(SharePreferences.getInstance(context)
                .getToken(), searchString, page, 10, 0, listener);
    }

    // UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    // Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initData() {// 必须在onCreate方法内调用
        super.initData();
        // 示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        tvBaseTitle.setText(title);

        // 示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    // Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    // Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void onRefresh() {
        searchString = "";
        drawer_search_input.setText("");
        ids = "";
        trackIds = "";
        super.onRefresh();
    }

    @Override
    public void initEvent() {// 必须在onCreate方法内调用
        super.initEvent();
        drawer_search_input.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable edit) {
                if (drawer_search_input.getText().toString().length() > 0) {
                    clear_ico.setVisibility(View.VISIBLE);
                    search_ico.setVisibility(View.GONE);
                    search_ico_right.setVisibility(View.VISIBLE);
                } else {
                    clear_ico.setVisibility(View.GONE);
                    search_ico.setVisibility(View.VISIBLE);
                    search_ico_right.setVisibility(View.GONE);
                }

            }
        });
        clear_ico.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                drawer_search_input.setText("");
                searchString = "";
                getListAsync(1);
            }
        });
        drawer_search_input
                .setOnEditorActionListener(new OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView textView,
                                                  int actionId, KeyEvent keyEvent) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            searchString = drawer_search_input.getText()
                                    .toString();
                            getListAsync(1);
                        }
                        return true;
                    }
                });
        search_ico_right.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                searchString = drawer_search_input.getText().toString();
                getListAsync(1);
            }
        });
        lvBaseList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // toActivity(FlowDetailActivity.createIntent(context,
                // listTodo.get(position-1).getWorkId(),
                // listTodo.get(position-1)
                // .getTitle(),listTodo.get(position-1).getTrackId()));

            }
        });
        rightButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String parm = "";
                Set<String> set = isCheckedMap.keySet();
                int i = 0;
                for (String check : set) {
                    parm += isCheckedMap.get(check).getId();
                    trackIds += isCheckedMap.get(check).getTrackId();
                    if (i < isCheckedMap.size() - 1) {
                        parm += ";";
                        trackIds += ";";
                    }
                    i++;

                }
                if (parm.length() > 0) {
                    ids = parm;
                    Intent intent = new Intent(context,
                            SearchAct.class);
                    startActivityForResult(intent, 11);
                } else {
                    showShortToast("请选择要移交的流程！");
                }

//				new AlertDialog(context, "接收操作", "你确定要接收吗？", true, 0,
//						dialogListener).show();
            }
        });
        // 示例代码>>>>>>>>>>>>>>>>>>>
    }


    @Override
    public void onDragBottom(boolean rightToLeft) {
        if (rightToLeft) {

            return;
        }

        finish();
    }

    @Override
    public void setList(final List<Agent> list) {
        listTodo = list;
        setList(new AdapterCallBack<MatterTransferAdapter>() {

            @Override
            public void refreshAdapter() {
                adapter.refresh(list);

            }

            @Override
            public MatterTransferAdapter createAdapter() {
                // TODO Auto-generated method stub
                return new MatterTransferAdapter(context, isCheckedMap);
            }
        });

    }

    OnHttpResponseListener recivelistener = new OnHttpResponseListener() {

        @Override
        public void onHttpResponse(int requestCode, String resultJson,
                                   Exception e) {
            boolean isNull = resultJson == null;
            if (resultJson != null) {
                Result result = JSON.parseObject(resultJson, Result.class);
                if (result.isSuccess())
                    showShortToast("移交成功！");
                else
                    showShortToast("移交失败！");
                onRefresh();
            } else {
                // progressDialog.cancel();
                showShortToast(e.getMessage());
            }
            onRefresh();
        }

    };

    OnHttpResponseListener listener = new OnHttpResponseListener() {

        @Override
        public void onHttpResponse(int requestCode, String resultJson,
                                   Exception e) {
            boolean isNull = resultJson == null;
            if (resultJson != null) {
                Result result = JSON.parseObject(resultJson, Result.class);
                if (result.isSuccess()) {
                    List<Agent> list = JSON.parseArray(result.getData()
                            .toString(), Agent.class);
                    onLoadSucceed(page, list);
                    // setList(list);
                } else {
                    showShortToast(result.getMessage());
                }
            } else {
                // progressDialog.cancel();
                if (e != null)
                    showShortToast(e.getMessage());
                else
                    showShortToast("连接服务器失败！");
            }
        }

    };

    @Override
    public List<Agent> parseArray(String json) {
        return JSON.parseArray(json, Agent.class);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 11:
                if (data != null) {
                    receiveUserId = data.getStringExtra("userId");
                    receiveUserName = data.getStringExtra("userName");
                    HttpRequest.matterTransfer(SharePreferences.getInstance(context).getToken(), receiveUserId, receiveUserName, ids, trackIds, 0, recivelistener);
                }
                break;
        }
    }
}